<template>
  <el-dialog
    model-value="dialogVisible"
    :title="dialogTitle"
    width="50%"
    @close="handleClose"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="公告标题" prop="title">
        <el-input
          v-model="form.title"
          type="text"
          maxlength="25"
          placeholder="请输入公告标题"
        />
      </el-form-item>
      <el-form-item label="公告内容" prop="content">
        <el-input
          v-model="form.content"
          :rows="4"
          type="textarea"
          placeholder="请输入公告内容"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleConfirm">确认</el-button>
        <el-button @click="handleClose">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script>
export default {
  name: "noticeDialog",
};
</script>
<script setup>
import { defineEmits, defineProps, ref, watch } from "vue";
import http, { getServerUrl } from "@/utils/request.js";
import { ElMessage } from "element-plus";

const tableData = ref([]);

const props = defineProps({
  id: {
    type: Number,
    default: -1,
    required: true,
  },
  dialogTitle: {
    type: String,
    default: "",
    required: true,
  },
  dialogVisible: {
    type: Boolean,
    default: false,
    required: true,
  },
});

const form = ref({
  id: -1,
  content: "",
  title: "",
});

const rules = ref({
  content: [{ required: true, message: "请输入公告内容" }],
  title: [{ required: true, message: "请输入公告标题" }],
});

const formRef = ref(null);

const initFormData = async (id) => {
  const res = await http.get("sys/notice/" + id);
  form.value = res.data.data;
};

watch(
  () => props.dialogVisible,
  () => {
    let id = props.id;
    if (id > 0) {
      initFormData(id);
    } else {
      form.value = {
        id: -1,
        content: "",
      };
      formRef && formRef.value && formRef.value.resetFields();
    }
  }
);

/*创建一个事件名为update:modelValue的initUserList事件*/
const emits = defineEmits(["update:modelValue", "getList"]);

const handleClose = () => {
  emits("update:modelValue", false);
};

const handleConfirm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      let result = null;
      let id = props.id;

      if (id < 0) {
        result = await http.post("sys/notice/add", form.value);
      } else {
        result = await http.post("sys/notice/edit", form.value);
      }
      let data = result.data;
      if (data.code == 200) {
        ElMessage.success(data.msg);
        formRef.value.resetFields();
        emits("getList");
        handleClose();
      } else {
        ElMessage.error(data.msg);
      }
    } else {
      console.log("fail");
    }
  });
};
</script>

<style lang="less" scoped>
</style>